import { WebSocketGateway, SubscribeMessage, MessageBody, WebSocketServer } from '@nestjs/websockets';
import { WebsocketService } from './websocket.service';
import { CreateWebsocketDto } from './dto/create-websocket.dto';
import { UpdateWebsocketDto } from './dto/update-websocket.dto';
import { MessageService } from 'src/message/message.service';
import { Server, Socket } from 'socket.io'
import { Logger } from '@nestjs/common';
@WebSocketGateway(4000, {
  cors: {
    origin: '*'
  }
})
export class WebsocketGateway {
  constructor(private readonly websocketService: WebsocketService, private readonly messageService: MessageService) { }
  @WebSocketServer() server: Server
  public connectionUsers = new Map<number, Socket>()
  private logger: Logger = new Logger('SocketGateway');



  //用户存在本地记录，之前没退出就关闭了浏览器导致
  @SubscribeMessage('reOpen')
  async reOpen(socket: Socket, userId: number) {
    this.logger.log(`user：${userId} reOpen`)
    this.connectionUsers.set(userId, socket)
    this.broadcastOnlineUserIds()
    const unReadCount = await this.messageService.unReadCount(userId)
    unReadCount > 0 && this.server.to(socket.id).emit('info', `您有${unReadCount}条未读消息`)
  }


  //登录
  @SubscribeMessage('login')
  async Connection(socket: Socket, userId: number) {
    this.logger.log(`user：${userId} login`)
    this.connectionUsers.set(Number(userId), socket)
    const unReadCount = await this.messageService.unReadCount(userId)
    unReadCount && this.server.to(socket.id).emit('info', `您有${unReadCount}条未读消息`)
    this.broadcastOnlineUserIds()
  } 
  @SubscribeMessage('sendMessage')
  sendMessage(socket: Socket, messageDto: {
    sessionDetail: { sender: any, receiver: any }, content: string, conversationId: number
  }) {
    const { sessionDetail: { sender, receiver }, content, conversationId } = messageDto
    const message = {
      sender,
      content,
      createdTime: new Date()
    }
    const userIdArrays = [sender.id, receiver.id]

    userIdArrays.forEach(async userId => {

      const client = this.connectionUsers.get(userId)
      // 在线
      // if (client) { 
      //接受端 触发消息接听事件
      if (userId !== sender.id) {
        if (client) {
          this.server.to(client.id).emit('info', `${sender.nickname}发来一条新的消息`)
          await this.messageService.handleMessage({
            senderId: sender.id, receiverId: receiver.id, conversationId, read: true, content: content
          })
          this.server.to(client.id).emit('receiveMessage', message)
        } else {
          //只能是对方不在线  存入未读消息1
          await this.messageService.handleMessage({
            senderId: sender.id, receiverId: receiver.id, conversationId, read: false, content: content
          })
        }
      } else {
        this.server.to(client.id).emit('receiveMessage', message)
      }
    })
  }





  @SubscribeMessage('loginOut')
  Disconnect(socket: Socket, userId: number) {
    this.logger.log(`Connection loginOut ${userId}`)
    this.connectionUsers.delete(userId)
    this.broadcastOnlineUserIds()
  }

  //用户断开连接 
  handleDisconnect(socket: Socket) {
    // 假设您有一个 socket 对象，您可以通过以下方式获取其 id：
    const socketId = socket.id;

    // 查找与 socketId 相关联的用户 id
    let userId: number | null = null;
    for (const [id, socket] of this.connectionUsers.entries()) {
      if (socket.id === socketId) {
        userId = id;
        break;
      }
    }
    // 如果找到了相关的用户 id，那么从 Map 中删除对应的项
    if (userId !== null) {
      this.connectionUsers.delete(userId);
      // 处理断开连接
      this.logger.log(`user ${userId} close broweser`)
    }
    this.broadcastOnlineUserIds()
  }


  @SubscribeMessage('onlineUsers')
  getOnlineUser(socket: Socket) {
    this.server.to(socket.id).emit('getOnlineUsers', Array.from(this.connectionUsers.keys()))
  }


  //像所有用户广播在线的用户Id
  private broadcastOnlineUserIds() {
    const onlineUserIds = Array.from(this.connectionUsers.keys());
    this.server.emit('onlineUserIds', onlineUserIds);
  }

}
